<?php
namespace Pm\Controllers;

use Helpers\Main;
use Helpers\Assets;
use Helpers\User;
use Admin\Models\pm\XhwoTemplate;
use Admin\Models\bpm\XHBpmTemplate;
use Admin\Models\pm\XhwoNode;
use Admin\Models\bpm\XHBpmNode;
use Admin\Models\pm\XhwoTemplateCount;
use Modules\Power;

class TemplateController extends ControllerBase
{
    private static $templateTypes = [
        1 => '通用',
        2 => '个人',
        3 => '部门',
    ];

    /**
     * 模板列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180704
     */
    public function indexAction()
    {
        if (!Power::exist('Pm_Work_Order_Template')) {
            return $this->sendViewError('权限不足', '无模板权限');
        }
        $this->di->get('assets')
            ->addCss('assets/sweetalert2/sweetalert2.min.css')
            ->addJs('assets/sweetalert2/sweetalert2.min.js');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        $this->view->pick('template/templateList');
        Assets::importJs('js/template/templateList.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        $this->view->setVars([
            'templateAdd'  => Power::exist('Pm_Work_Order_Template_Add'),
            'templateEdit' => Power::exist('Pm_Work_Order_Template_Edit'),
            'templateDel'  => Power::exist('Pm_Work_Order_Template_Del'),
        ]);
    }

    /**
     * 获取模板列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180704
     */
    public function getTemplateAction()
    {
        try {
            if (!Power::exist('Pm_Work_Order_Template')) {
                return $this->sendErrorResponse(500, '权限不足', '无模板权限');
            }
            $sName = $this->request->getPost('sName', 'string'); //根据
            $userId = Main::getLoginUserInfo('userId');
            $extraDeps = User::getextrapower('dep', 'workorderTemplate');//取扩展部门权限
            $depIds = Main::getLoginUserInfo('depId');
            $deps = array_merge($extraDeps, $depIds);
            $deps   = implode(",%' OR  sDepIds like '%,", $deps);
            $condition = " bDelete = 0";
            $condition .= $sName ? " AND sTPName LIKE '%$sName%'" : '';
            $condition .= " AND ((sDepIds like '%,".$deps.",%' AND iType=3) OR (iType=1)  OR (iType=2 AND iCreateUserId= $userId) ) ";//部门 通用 个人
            $condition1  = " bDelete=0 AND iTPId = :iTPId:";
            $builder = $this->modelsManager->createBuilder()
//                ->addFrom('Admin\Models\pm\XhwoTemplate')
                ->columns('iTPId as iId,sTPName as sName,tCreateDate,tLastModifyDate')
                ->addFrom('Admin\Models\bpm\XHBpmTemplate')
                ->where($condition);
            $data = Main::runBuilderPages($builder, true);
            foreach ($data['rows'] as $key => $value) {
                $data['rows'][$key]['sContent'] = '';
                $data['rows'][$key]['primaryKey'] = 'T'.$value['iId'];
                $data['rows'][$key]['type'] = 1;
                $data['rows'][$key]['sRemarks'] = '';
                $data['rows'][$key]['iTPId'] = 0;
                $objs = XHBpmNode::find([
                    'columns' => 'iNodeId as iId,sNodeName as sName,sContent,
                    mDesc as sRemarks,tCreateDate,tLastModifyDate',
                    'conditions' => $condition1,
                    'bind' => array('iTPId' => $value['iId']),
                ])->toArray();
                $data['rows'][$key]['state'] = empty($objs) ?  '' : "closed";
                $data['rows'][$key]['iconCls'] = empty($objs) ? 'fa fa-file-text' : 'fa fa-folder';
                $data['rows'][$key]['children'] = $this->getTemplateNodes($value['iId']);
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());
        }
    }

    /**
     * 获取模板节点
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180705
     */
    private function getTemplateNodes($id)
    {
        $condition   = "bDelete=0 AND iTPId = :iTPId: ";
        $param= array('iTPId' => $id);
        $data = $this->modelsManager->createBuilder()
                ->addFrom('Admin\Models\bpm\XHBpmNode')
                ->columns('iNodeId as iId,sNodeName as sName,sContent,mDesc as sRemarks,tCreateDate,tLastModifyDate')
                ->where($condition, $param)
                ->getQuery()
                ->execute()
                ->toArray();
        foreach ($data as $k => $v) {
            $data[$k]['iconCls'] = 'fa fa-file-text';
            $data[$k]['primaryKey'] = 'N'.$v['iId'];
            $data[$k]['type'] = 2;
        }
        return $data;
    }

    /**
     * 新建/编辑 模板表单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180704
     */
    public function templateFormAction()
    {
        $iId = $this->request->getQuery('iId', 'int');
        if ($iId) {
            if (!Power::exist('Pm_Work_Order_Template_Edit')) {
                return $this->sendViewError('权限不足', '无编辑模板权限');
            }
        } else {
            if (!Power::exist('Pm_Work_Order_Template_Add')) {
                return $this->sendViewError('权限不足', '无新增模板权限');
            }
        }
        Assets::easyUI();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/template/templateForm.js');
        $this->view->pick('template/templateForm');
        $this->view->setVars([
            'iId' => $iId,
            'templateTypes' => self::$templateTypes,
        ]);
    }

    /**
     * 新建/编辑模板
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180704
     */
    public function saveTemplateAction()
    {
        $iId = $this->request->getPost('iTPId', 'int');
        //项目创建人id  && name
        try {
            $this->db->begin();  //开启事务
            if ($iId) {
                if (!Power::exist('Pm_Work_Order_Template_Edit')) {
                    return $this->sendErrorResponse(500, '权限不足', '无编辑模板权限');
                }
                $template = XHBpmTemplate::findFirst($iId);
                if (!$template) {
                    return $this->sendErrorResponse(400, '参数错误', '模板不存在');
                }
            } else {
                if (!Power::exist('Pm_Work_Order_Template_Add')) {
                    return $this->sendErrorResponse(500, '权限不足', '无新增模板权限');
                }
                $template = new XHBpmTemplate();
            }
            $template->assign($this->request->getPost());
            $depIds = Main::getLoginUserInfo('depId');
            if ($depIds) {
                $iDepIds = implode(',', $depIds);
                $template->sDepIds = ','.$iDepIds.',';
                $template->sTag = 'workOrder';
            }
            $result = $template->save();
            if (!$result) {
                $this->db->rollback();
                return $iId ? $this->sendErrorResponse(500, '编辑模板失败') : $this->sendErrorResponse(500, '创建模板失败');
            }
            if (!$iId) {
                $templateCount = new XhwoTemplateCount();
                $templateCount->iTemplateId = $template->iTPId;
                $res = $templateCount->save();
                if (!$res) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '创建模板失败');
                }
            }
            $this->db->commit();
            return $iId ? $this->sendSuccessResponse('编辑模板成功') : $this->sendSuccessResponse('创建模板成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $iId ?
                $this->sendErrorResponse(500, '编辑模板失败', $exception->getMessage()) :
                $this->sendErrorResponse(500, '创建模板失败', $exception->getMessage());
        }
    }

    /**
     * 获取已存在的模板
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk  20180704
     */
    public function getTemplateInfoAction()
    {
        try {
            $iId = $this->request->getPost('iId', 'int');
            if (!$iId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XHBpmTemplate::findFirst($iId);
            $data = $obj ? $obj->toArray() : [];
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取产品信息失败', $exception->getMessage());
        }
    }

    /**
     * 删除模板
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180704
     */
    public function delTemplateByIdAction()
    {
        if (!Power::exist('Pm_Work_Order_Template_Del')) {
            return $this->sendErrorResponse(500, '权限不足', '无删除模板权限');
        }
        $iId = $this->request->getPost('iId', 'int');
        try {
            $template = XHBpmTemplate::findFirst([
                'conditions' => "bDelete = 0 AND iTPId = $iId"
            ]);
            if (!$template) {
                return $this->sendErrorResponse(400, '参数错误');
            }
            $this->db->begin();
            $template->bDelete = 1;
            $re = $template->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除失败');
            }
            $this->db->commit();
            return $this-> sendSuccessResponse('删除成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

    ##################################################模板节点相关######################################################

    /**
     * 新建/编辑 模板节点表单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180704
     */
    public function nodeFormAction()
    {
        $iId = $this->request->getQuery('iId', 'int');
        $templateId = $this->request->getQuery('iTemplateId', 'int');
        if ($iId) {
            if (!Power::exist('Pm_Work_Order_Template_Edit')) {
                return $this->sendViewError('权限不足', '无编辑节点权限');
            }
        } else {
            if (!Power::exist('Pm_Work_Order_Template_Add')) {
                return $this->sendViewError('权限不足', '无新增节点权限');
            }
        }
        Assets::easyUI();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/template/nodeForm.js');
        $this->view->pick('template/nodeForm');
        $this->view->setVars([
            'iId' => $iId,
            'templateId' => $templateId,
        ]);
    }

    /**
     * 新建/编辑节点
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180704
     */
    public function saveNodeAction()
    {
        $iId = $this->request->getPost('iNodeId', 'int');
        //项目创建人id  && name
        try {
            $this->db->begin();  //开启事务
            if ($iId) {
                if (!Power::exist('Pm_Work_Order_Template_Edit')) {
                    return $this->sendErrorResponse(500, '权限不足', '无编辑节点权限');
                }
                $node = XHBpmNode::findFirst($iId);
                if (!$node) {
                    return $this->sendErrorResponse(400, '参数错误！');
                }
            } else {
                if (!Power::exist('Pm_Work_Order_Template_Add')) {
                    return $this->sendErrorResponse(500, '权限不足', '无新增节点权限');
                }
                $node = new XHBpmNode();
            }
            $node->assign($this->request->getPost());
            $result = $node->save();
            if (!$result) {
                $this->db->rollback();
                return $iId ? $this->sendErrorResponse(500, '编辑节点失败')
                    : $this->sendErrorResponse(500, '创建节点失败');
            }
            $this->db->commit();
            return $iId ? $this->sendSuccessResponse('编节点板成功') : $this->sendSuccessResponse('创建节点成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $iId ?
                $this->sendErrorResponse(500, '编辑节点失败', $exception->getMessage()) :
                $this->sendErrorResponse(500, '创建节点失败', $exception->getMessage());
        }
    }


    /**
     * 删除节点
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180704
     */
    public function delNodeByIdAction()
    {
        if (!Power::exist('Pm_Work_Order_Template_Del')) {
            return $this->sendErrorResponse(500, '权限不足', '无删除节点权限');
        }
        $iId = $this->request->getPost('iId', 'int');
        try {
            $node = XHBpmNode::findFirst([
                'conditions' => "bDelete = 0 AND iNodeId = $iId"
            ]);
            if (!$node) {
                return $this->sendErrorResponse(400, '参数错误');
            }
            $this->db->begin();
            $node->bDelete = 1;
            $re = $node->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

    /**
     * 获取已存在的模板节点
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk  20180705
     */
    public function getNodeInfoAction()
    {
        try {
            $iId = $this->request->getPost('iId', 'int');
            if (!$iId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XHBpmNode::findFirst($iId);
            $data = $obj ? $obj->toArray() : [];
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取产品信息失败', $exception->getMessage());
        }
    }
}

